<template>
  <div>
    <el-card>
      <el-page-header title="成绩管理" @back="router.back()" style="margin-bottom: 20px">
        <template #content>
          <span class="text-large font-600 mr-3">录入成绩</span>
        </template>
      </el-page-header>

      <el-row>
        <el-col :span="4">课程编号：{{ courseData.courseid }}</el-col>
        <el-col :span="4">课程名称：{{ courseData.coursename }}</el-col>
        <el-col :span="4">学分：{{ courseData.credit }}</el-col>
        <el-col :span="4">成绩类型：{{ courseData.type === 1 ? '百分制' : '等级划分制' }}</el-col>
        <el-col :span="4">专业名称：{{ courseData.major }}</el-col>
        <el-col :span="4">任课教师：{{ courseData.name }}</el-col>
      </el-row>

      <el-form>
        <el-table :data="tableData" style="width: 100%" stripe v-loading="loading">
          <el-table-column prop="classes" label="班级" />
          <el-table-column prop="username" label="学号" />
          <el-table-column prop="name" label="姓名" />
          <el-table-column label="平时成绩">
            <template #default="scope">
              <el-form-item style="margin: auto" v-if="num1">
                <el-input v-model.number="scope.row.daily" placeholder="Please input" oninput="if(value > 100) value = 100; if(value < 0 || value == '' || value == null) value = 0;" :maxlength="3" :minlength="1" />
              </el-form-item>
              <el-form-item style="margin: auto" v-else> — </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="实验成绩">
            <template #default="scope">
              <el-form-item style="margin: auto" v-if="num2">
                <el-input v-model.number="scope.row.exp" placeholder="Please input" oninput="if(value > 100) value = 100; if(value < 0 || value == '' || value == null) value = 0;" :maxlength="3" :minlength="1" />
              </el-form-item>
              <el-form-item style="margin: auto" v-else> — </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="期中成绩">
            <template #default="scope">
              <el-form-item style="margin: auto" v-if="num3">
                <el-input v-model.number="scope.row.mid" placeholder="Please input" oninput="if(value > 100) value = 100; if(value < 0 || value == '' || value == null) value = 0;" :maxlength="3" :minlength="1" />
              </el-form-item>
              <el-form-item style="margin: auto" v-else> — </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="期末成绩">
            <template #default="scope">
              <el-form-item style="margin: auto" v-if="num4 && courseData.type === 1">
                <el-input v-model.number="scope.row.final" placeholder="Please input:" oninput="if(value > 100) value = 100; if(value < 0 || value == '' || value == null) value = 0;" :maxlength="3" :minlength="1" />
              </el-form-item>
              <el-form-item style="margin: auto" v-else-if="num4 && courseData.type === 2">
                <el-select v-model="scope.row.final" class="m-2" placeholder="Select">
                  <el-option v-for="item in ScoreOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item style="margin: auto" v-else> — </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="courseid" label="总评">
            <template #default="scope">
              <div style="margin: auto" v-if="courseData.type === 1">
                {{ total(scope.row) }}
              </div>
              <div style="margin: auto" v-else>
                {{ level(scope.row) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="courseid" label="绩点">
            <template #default="scope">
              <div style="margin: auto; color: red; background-color: yellow" v-if="total(scope.row) < 60">0</div>
              <div style="margin: auto" v-else>
                {{ ((total(scope.row) - 50) / 10).toFixed(2) }}
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item style="margin-top: 20px">
          <el-button type="info" @click="handlePreSummit()">暂存</el-button>
          <el-button type="primary" @click="handleSummit()">上传</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
const router = useRouter()
const route = useRoute()
const courseData = ref({})
const tableData = ref([])
const loading = ref(true)
const num1 = ref(0) //平时成绩
const num2 = ref(0) //实验成绩
const num3 = ref(0) //期中成绩
const num4 = ref(0) //期末成绩
const total = (data) => {
  data.daily = data.daily ? Number(data.daily) : 0
  data.exp = data.exp ? Number(data.exp) : 0
  data.mid = data.mid ? Number(data.mid) : 0
  data.final = data.final ? Number(data.final) : 0
  const sum = data.daily * num1.value + data.exp * num2.value + data.mid * num3.value + data.final * num4.value
  return sum / 10
}
const level = ({ final }) => {
  switch (final) {
    case 95:
      return '优秀'
      break
    case 85:
      return '良好'
      break
    case 75:
      return '中等'
      break
    case 65:
      return '及格'
      break
    case 0:
      return '不及格'
      break
  }
}
const ScoreOptions = [
  { label: '优秀', value: 95 },
  { label: '良好', value: 85 },
  { label: '中等', value: 75 },
  { label: '及格', value: 65 },
  { label: '不及格', value: 0 }
]

onMounted(async () => {
  await getCourseData()
  await getTableData()
  // console.log(courseData.value)
  // console.log(tableData.value)
  handleSetRatio()
})
const getCourseData = async () => {
  const res1 = await axios.get(`/api/course/list/${route.params.id}`)
  // console.log(res.data.data[0])
  const res2 = await axios.get('/api/user/getteacherlist')
  // 将教师工号改为名字
  res1.data.data.forEach((item) => {
    res2.data.data.forEach((i) => {
      if (item['courseteacher'] === i['username']) {
        item['name'] = i['name']
      }
    })
  })
  courseData.value = res1.data.data[0]
  // console.log(courseData.value)
}
const getTableData = async () => {
  // console.log(courseData.value)
  const res1 = await axios.get(`/api/student/scorelist/${courseData.value.major}`)
  const res2 = await axios.get('/api/user/getstudentlist')
  const res3 = await axios.get(`/api/score/list/${courseData.value.courseid}`)
  // 附上学生名字
  res1.data.data.forEach((item) => {
    res2.data.data.forEach((i) => {
      if (item['username'] === i['username']) {
        item['name'] = i['name']
      }
    })
  })
  // 附上成绩信息
  res1.data.data.forEach((item) => {
    res3.data.data.forEach((i) => {
      if (item['username'] === i['username']) {
        Object.assign(item, i)
      }
    })
  })
  tableData.value = res1.data.data
  loading.value = false

  // console.log(tableData.value)
}
const handleSetRatio = () => {
  if (courseData.value.ratio) {
    let arr = courseData.value.ratio.split(',')
    // console.log(arr)
    num1.value = Number(arr[0])
    num2.value = Number(arr[1])
    num3.value = Number(arr[2])
    num4.value = Number(arr[3])
  }
}
const handlePreSummit = async () => {
  // ispublish为0
  // console.log(tableData.value)
  // console.log(courseData.value.courseid)
  tableData.value.forEach(async (item) => {
    // console.log(item)
    item.ispublish = 0
    item.reexam = 0
    if (total(item) < 60) {
      item.ispass = 0
    } else {
      item.ispass = 1
    }
    const res = await axios.post(`/api/score/find/${courseData.value.courseid}`, item)
    // console.log(res.data)
    if (res.data.data.length === 0) {
      // 数据库中没有数据
      await axios.post(`/api/score/list/${courseData.value.courseid}`, item)
    } else {
      await axios.put(`/api/score/list/${courseData.value.courseid}`, item)
    }
  })
  ElMessage.success('暂存成功！')
  router.push(`/score-manage/addscore`)
}
const handleSummit = () => {
  // ispublish为1
  // console.log(tableData.value)
  tableData.value.forEach(async (item) => {
    // console.log(item)
    item.ispublish = 1
    item.reexam = 0
    if (total(item) < 60) {
      item.ispass = 0
    } else {
      item.ispass = 1
    }
    const res = await axios.post(`/api/score/find/${courseData.value.courseid}`, item)
    // console.log(res.data)
    if (res.data.data.length === 0) {
      // 数据库中没有数据
      await axios.post(`/api/score/list/${courseData.value.courseid}`, item)
    } else {
      await axios.put(`/api/score/list/${courseData.value.courseid}`, item)
    }
  })
  // 更新课程发布状态
  axios.put(`/api/course/ispublish/${courseData.value.courseid}`, { ispublish: 1 })
  ElMessage.success('发布成功！')
  router.push(`/score-manage/addscore`)
}
</script>

<style lang="scss" scoped>
::v-deep .el-table .el-table__cell {
  text-align: center;
}
::v-deep .el-form-item__content {
  justify-content: center;
}
</style>
